package pers.myutil.network.request;



import pers.myutil.local.conversion.data.MapConversion;
import pers.myutil.throwable.network.MyUtilNetworkException;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 网络请求
 */
public class NetworkRequest  {

    /**
     * 带参数的HTTP请求地址
     * @param url 请求地址
     * @param requestMethod 请求方式
     * @param param 请求参数
     * @return 请求结果
     * @throws MyUtilNetworkException
     */
    public static String sendHttp(String url, RequestMethod requestMethod, String param) throws IOException, MyUtilNetworkException {
        return HttpRequest.send(url, requestMethod, param);
    }

    /**
     * 带参数请求地址
     * @param url 请求地址
     * @param requestMethod 请求方式
     * @param param 请求参数
     * @return 请求结果
     * @throws MyUtilNetworkException
     */
    public static String send(String url, RequestMethod requestMethod, String param) throws MyUtilNetworkException, IOException {
        if(Pattern.compile("http://[^\\s]*").matcher(url).matches()){
            return sendHttp(url, requestMethod, param);
        }else {
            return sendHttp(url, requestMethod, param);
        }
    }

    /**
     * 带参数MapHTTP请求
     * @param url 请求地址
     * @param requestMethod 请求方式
     * @param param 请求参数Map
     * @return 请求结果
     * @throws MyUtilNetworkException
     */
    public static String sendHttp(String url, RequestMethod requestMethod, Map<String ,Object> param) throws MyUtilNetworkException, IOException {
        return sendHttp(url, requestMethod, MapConversion.mapToString(param));
    }

    /**
     * 带参数Map请求
     * @param url 请求地址
     * @param requestMethod 请求方式
     * @param param 请求参数Map
     * @return 请求结果
     * @throws MyUtilNetworkException
     */
    public static String send(String url, RequestMethod requestMethod, Map<String ,Object> param) throws MyUtilNetworkException, IOException {
        return send(url, requestMethod,MapConversion.mapToString(param));
    }

    /**
     * 不带参数请求地址
     * @param url 请求地址
     * @param requestMethod 请求方式
     * @return 请求结果
     * @throws MyUtilNetworkException
     */
    public static String sendHttp(String url, RequestMethod requestMethod) throws MyUtilNetworkException, IOException {
        return sendHttp( url,  requestMethod, (String) null);
    }

    /**
     * 不带参数请求地址
     * @param url 请求地址
     * @param requestMethod 请求方式
     * @return 请求结果
     * @throws MyUtilNetworkException
     */
    public static String send(String url, RequestMethod requestMethod) throws MyUtilNetworkException, IOException {
        return send( url,  requestMethod, (String) null);
    }



    public static void main(String[] a) throws IOException, MyUtilNetworkException {
//        Map map = new HashMap();
//        map.put("userToken","9a1e9c74f2dd485390dba5f655a8d941");
////        System.out.println(NetworkRequest.send("http://192.168.7.152:8080/user/findUserList", RequestMethod.GET, "userToken=9a1e9c74f2dd485390dba5f655a8d941"));
////        System.out.println(NetworkRequest.send("http://192.168.7.152:8080/user/findUserList", RequestMethod.GET, map));
////        System.out.println( NetworkRequest.send("http://ip.chinaz.com/getip.aspx",RequestMethod.GET));
//        System.out.println( NetworkRequest.send("http://www.baidu.com",RequestMethod.GET, (String) null));
////        System.out.println( NetworkRequest.send("http://192.168.7.152:8080/role/save?",RequestMethod.POST,"userToken=9a1e9c74f2dd485390dba5f655a8d941&name=管理员2"));

//        String APPID = "wxb4ad05412ea72c2d";
//        String SECRET = "d0c43cf0ea2008f9c3f126c2c42fa523";
//        String url = "https://api.weixin.qq.com/sns/jscode2session";
//        String CODE = "061IzA482BhinR0L6q4820uV482IzA4s";
//        Map map = new HashMap();
//        map.put("appid",APPID);
//        map.put("secret",SECRET);
//        map.put("js_code",CODE);
//        map.put("grant_type","authorization_code");
//        System.out.println(NetworkRequest.send(url,RequestMethod.GET,map));
    }

}

class HttpRequest{

    /**
     * http代理请求
     * @param httpUrl 请求地址
     * @param requestMethod 请求方式
     * @param param 请求参数
     * @param proxyIp 代理IP
     * @param post 代理端口
     * @return 请求返回数据
     * @throws IOException 数据异常
     * @throws MyUtilNetworkException 公共异常
     */
    public static String send(String httpUrl,RequestMethod requestMethod,String param,String proxyIp,int post) throws IOException, MyUtilNetworkException {
        if(requestMethod.equals(RequestMethod.GET)){
            if(param != null && !"".equals(param))  httpUrl = httpUrl+"?"+param;
        }
        URL url = new URL(httpUrl);
        HttpURLConnection connection;
        if(proxyIp != null && post != 0) {
            InetSocketAddress addr = new InetSocketAddress(proxyIp, post);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
            connection = (HttpURLConnection) url.openConnection(proxy);
        }else {
            connection = (HttpURLConnection) url.openConnection();
        }
        // 设置通用的请求属性
        connection.setRequestMethod(requestMethod.getRequestMethod());
        if(connection.getRequestMethod().equals(RequestMethod.POST.getRequestMethod())) {
            if(param == null || param.equals("")){
                throw new MyUtilNetworkException("请求参数不能为空！");
            }
            //设置允许写出数据,默认是不允许 false
            connection.setDoOutput(true);
            connection.setDoInput(true);
            OutputStream os = connection.getOutputStream();
            //参数是键值队  , 不以"?"开始
            os.write(param.getBytes());
            os.flush();
        }else {
            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");
        }
        //设置相应时间
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);

        // 建立连接
        connection.connect();

        if(connection.getResponseCode() != 200){
            throw new MyUtilNetworkException("请求异常！错误代码："+connection.getResponseCode());
        }

        BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String temp;
        while ((temp = reader.readLine()) != null) {
            stringBuilder.append(temp);
//            sbf.append("\r\n");
        }
        connection.disconnect();
        return stringBuilder.toString();
    }

    /**
     * 不带代理请求
     * @param httpUrl 请求地址
     * @param requestMethod 请求方式
     * @param param 请求参数
     * @return 请求后的数据
     * @throws IOException
     * @throws MyUtilNetworkException
     */
    public static String send(String httpUrl,RequestMethod requestMethod,String param) throws IOException, MyUtilNetworkException {
        return send(httpUrl, requestMethod, param,null,0);
    }
}
